import React from 'react'
import _ from 'lodash'
import { LinkWidget } from 'react-js-diagrams'

export class FlowLinkLayerWidget extends React.Component {
    generateLinks () {
        const engine = this.props.diagramEngine
        const diagramModel = engine.getDiagramModel()


        return _.map(diagramModel.getLinks(), link => {
            // TODO: just improve this vastly x_x
            let sourceCenter = engine.getPortCenter(link.sourcePort, link.points[0])
            let targetCenterPoint = engine.getPortCenter(link.targetPort, link.points[1])

            if(sourceCenter){
                link.sourceCenterPoint = sourceCenter
            }

            if(targetCenterPoint){
                link.targetCenterPoint = targetCenterPoint
            }

            if (link.sourcePort !== null) {
                try {
                    //generate a point
                    let properSourceJoint = engine.getSourceJointPoint(link.sourcePort, targetCenterPoint)

                    link.points[0].updateLocation(properSourceJoint)
                }
                    // Remove the link because its problematic (TODO implement this rather at an engine level)
                catch (ex) {
                    diagramModel.removeLink(link)
                    return
                }
            }
            if (link.targetPort !== null) {
                try {
                    let propertTargetJoint = engine.getTargetJointPoint(link.targetPort, sourceCenter)
                    _.last(link.points).updateLocation(propertTargetJoint)
                }
                    //remove the link because its problematic (TODO implement this rather at an engine level)
                catch (ex) {
                    diagramModel.removeLink(link)
                    return
                }
            }

            // Generate the links
            const generatedLink = this.props.diagramEngine.generateWidgetForLink(link)
            if (!generatedLink) {
                return null
            }

            const props = {
                key: link.getID(),
                link,
                diagramEngine: this.props.diagramEngine,
            }

            return (
                <LinkWidget {...props}>
                    {React.cloneElement(generatedLink, { pointAdded: this.props.pointAdded })}
                </LinkWidget>
            )
        })
    }

    render () {
        const diagramModel = this.props.diagramEngine.getDiagramModel()
        const zoom = diagramModel.getZoomLevel()
        const offsetX = diagramModel.getOffsetX()
        const offsetY = diagramModel.getOffsetY()
        const svgStyle = {
            transform: `scale(${zoom / 100.0}) translate(${offsetX}px, ${offsetY}px)`,
            width: '100%',
            height: '100%',
        }

        return (
            <svg style={svgStyle}>
                {this.generateLinks()}
            </svg>
        )
    }
}
